<template>
  <div class="fix-width-frame">
    <div class="main-content f-cb">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="金币充值" name="first">
          <div class="balance">
            您的账户余额：
            <span style="color:red">{{balance / 100}}</span>
          </div>

          <div class="tip">
            <span>充值须知：</span>1、二维码有效期5分钟，请在规定时间内下单；2、正常到账时间为1分钟，若超时，请联系客服
          </div>
          <div class="tip">
            <span>充值须知：</span>由于支付宝限制，推荐使用输入任意金额充值。
          </div>
          <el-dropdown @command="handleCommand">
            <span class="el-dropdown-link">
              充值方式切换
              <i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="any">任意金额</el-dropdown-item>
              <el-dropdown-item command="fix">固定金额</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

          <div class="deposit-any" v-if="inputType">充值金额：
            <el-input placeholder="请输入充值金额" v-model="depositValue" style="width: 250px;"/>
          </div>
          <div class="deposit-list" v-else>
            <div v-for="item of allValues" :key="item.value+item.selected" class="deposit-item">
              <payOption
                :value="item.value"
                :selected="item.selected"
                @selectValue="payValueChange"
              ></payOption>
            </div>
          </div>
          <div class="pay-container">
            <el-button class="payButton" type="primary" @click="submitForm">立即充值</el-button>
          </div>

          <el-dialog
            title="付款信息"
            :visible.sync="showQr"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            :before-close="handleClose"
            @open="afterOpen"
          >
            <el-row>
              <el-col :span="8">
                <img src="../../assets/img/alipay.jpg" class="image">
              </el-col>
            </el-row>
            <el-row type="flex" justify="space-between" class="lineBox">
              <el-col :span="8">
                <div>
                  <span>订单超时剩余： {{timeOver}}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div style="text-align: right;">
                  <span style="color: red;">支付金额：</span>
                  <span>{{realOrderMoney}}元</span>
                </div>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12" :offset="6">
                <div class="center">
                  <span>此二维码支付一次有效</span>
                </div>
              </el-col>
            </el-row>

            <el-row>
              <div class="center">
                <canvas ref="canvas" style="width: 300px; height: 300px"></canvas>
              </div>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12" :offset="6">
                <div class="center">
                  <span>订单号: {{youyunbaoId}}</span>
                </div>
              </el-col>
            </el-row>

            <div></div>
          </el-dialog>
        </el-tab-pane>
        <!--<el-tab-pane label="查看帐户明细" name="second">查看帐户明细</el-tab-pane>-->
        <el-tab-pane label="充值记录" name="third">
          <div class="table_container">
            <el-table
              v-loading="tableLoading"
              :data="tableData"
              highlight-current-row
              style="width: 100%"
            >
              <!-- <el-table-column
                              type="index"
                              width="100">
              </el-table-column>-->
              <el-table-column property="gmtCreate" label="充值时间" width="180"></el-table-column>
              <el-table-column label="充值类型" width="120">
                <template slot-scope="scope">{{valueForTransType(scope.row.transType)}}</template>
              </el-table-column>
              <el-table-column label="充值金额" width="150">
                <template slot-scope="scope">{{(scope.row.transAmount/100).toFixed(2)}}</template>
              </el-table-column>
              <el-table-column label="充值后余额" width="150">
                <template slot-scope="scope">{{(scope.row.balanceAfter/100).toFixed(2)}}</template>
              </el-table-column>
              <el-table-column label="单号">
                <template slot-scope="scope">{{scope.row.outerId}}</template>
              </el-table-column>
            </el-table>
            <div class="Pagination" style="text-align: left;margin-top: 10px;">
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-size="limit"
                :page-count="10"
                layout="total, prev, pager, next"
                :total="count"
              ></el-pagination>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import headTop from "@/components/headTop";
import payOption from "@/components/payOption";
import { orderDeposit } from "@/api/order";
import { getAccountLog, getPayInfo, checkPayInfo } from "@/api/points";
import QRCode from "qrcode";
import { getUserAccount } from "@/api/myinfo";
import { transtypeDescription } from "@/utils/constants";
import { mapGetters } from "vuex";

// import qs from 'qs'
// import axios from 'axios'
// import { YYBIDS } from '@/utils/constants'

export default {
  data() {
    return {
      balance: "",
      inputType: true,
      allValues: [
        {
          value: 10,
          selected: false
        },
        {
          value: 50,
          selected: false
        },
        {
          value: 100,
          selected: true
        },
        {
          value: 500,
          selected: false
        },
        {
          value: 1000,
          selected: false
        },
        {
          value: 5000,
          selected: false
        }
        // {
        //   value: 10000,
        //   selected: false
        // }
      ],
      activeName: "first",
      depositValue: 100,
      formData: {
        orderCode: "200101",
        orderAmount: 0,
        outAmount: 0
      },

      orderId: "",

      tableData: [],
      currentRow: null,
      offset: 0,
      limit: 20,
      count: 0,
      currentPage: 1,
      tableLoading: true,
      // temp_amount: '',
      showQr: false,
      youyunbaoId: null,
      payUrl: "",
      realOrderMoney: 0,
      checkInterval: null,
      timeOver: "",
      timeOverInterval: null,
      ordertime: ""
    };
  },
  // computed: mapGetters(['getConfigByKey']),
  components: {
    headTop,
    payOption
  },
  mounted() {
    this.initData();
  },
  methods: {
    handleClick(tab, event) {},
    initData() {
      this.getAccountLog(this.currentPage, this.limit);
      this.getBalance();
    },
    payValueChange(newValue) {
      this.depositValue = newValue;
      let all = this.allValues.map(v => {
        if (v.value === newValue) {
          v.selected = true;
        } else {
          v.selected = false;
        }
        return v;
      });
      this.allValues = all;
      // this.allValues.splice(0, 7, ...all)
    },
    async getBalance() {
      try {
        // const account = await getAccount();
        const result = await getUserAccount();
        if (result.status === 200 && result.data.code === 200) {
          let data = result.data;
          this.balance = data.data.balance;
        }
      } catch (err) {
        console.log(err);
      }
    },
    async getAccountLog(page, size) {
      // let d = {
      //   userAccountId: window.userId
      // }
      this.tableLoading = true;
      let params = {
        pageIndex: page,
        pageSize: size,
        transDirection: "IN",
        userId: this.$route.id
      };
      let result = await getAccountLog(params);
      if (result.status === 200) {
        let data = result.data.data;

        this.tableData = data;
        this.count = result.data.page.total;
      }
      this.tableLoading = false;
    },
    async submitForm() {
      let loading = this.$loading({
        lock: true,
        text: "正在加载",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });

      this.formData.outAmount = (this.depositValue * 100).toFixed(0);
      this.formData.orderAmount = (this.depositValue * 100).toFixed(0);
      try {
        let result = await orderDeposit(this.formData);
        if (result.data.code === 200) {
          this.orderId = result.data.data.id;
          // this.payFormData.money = this.temp_amount
          // this.payFormData.data = this.orderId
          // this.doYouyunNetPay()
          this.getPayInfo();
          loading.close();
        } else {
          this.$notify.error({
            title: "错误",
            message: result.data.title,
            offset: 100
          });
          loading.close();
        }
      } catch (error) {
        loading.close();
      }
    },
    async getPayInfo() {
      try {
        let result = await getPayInfo({
          id: this.orderId,
          ip: window.returnCitySN.cip,
          appId: this.$store.getters.getConfigByKey("youyunbaoid"),

          type: 1
        });
        if (result.status === 200 && result.data.code === 200) {
          let returnJson = JSON.parse(result.data.data);
          if (returnJson.state === "1") {
            this.showQr = true;

            this.youyunbaoId = returnJson.order;
            this.payUrl = returnJson.qrcode;
            this.realOrderMoney = returnJson.money;
            this.ordertime = returnJson.times;
            this.countTime();
            this.checkInterval = setInterval(() => {
              this.checkPayInfo();
            }, 3000);
          } else {
          }
        } else {
          throw new Error("获取支付信息失败");
        }
      } catch (error) {
        this.$notify.error({
          title: "错误",
          message: "获取支付信息失败",
          offset: 100
        });
      }
    },
    async checkPayInfo() {
      try {
        let result = await checkPayInfo({
          order: this.youyunbaoId,
          ip: window.returnCitySN.cip,
          appId: this.$store.getters.getConfigByKey("youyunbaoid"),
          type: 1
        });
        if (result.status === 200 && result.data.code === 200) {
          let returnJson = JSON.parse(result.data.data);
          if (returnJson.code === "1") {
            clearInterval(this.checkInterval);
            this.$message({
              message: "支付成功",
              type: "success"
            });
            this.showQr = false;
            this.currentPage = 0;
            this.getAccountLog(this.currentPage, this.limit);
          } else if (returnJson.code === "2" || returnJson.code === "3") {
            this.$notify.error({
              title: "错误",
              message: "支付失败，请重试",
              offset: 100
            });
            clearInterval(this.checkInterval);
            this.showQr = false;
          } else if (returnJson.code === "4") {
            clearInterval(this.checkInterval);
            this.showQr = false;
          }
        } else {
        }
      } catch (error) {
        console.log(error);
      }
    },
    // doYouyunNetPay () {
    //   setTimeout(function () { document.myform.submit() }, 500)
    //
    //                let result = await doYouyunNetPay(this.payFormData);
    //                if (result.data.code == 200) {
    //
    //                }
    // },
    valueForTransType(type) {
      return transtypeDescription(type);
    },
    handleCurrentChange(page) {
      console.log(page);
      this.currentPage = page;
      this.getAccountLog(this.currentPage, this.limit);
    },

    handleSizeChange(page) {
      console.log(page);
      this.getAccountLog(this.currentPage, this.limit);
    },
    handleClose(done) {
      this.$confirm("确认退出支付吗？")
        .then(_ => {
          if (this.checkInterval !== null) {
            clearInterval(this.checkInterval);
          }
          done();
        })
        .catch(_ => {});
    },
    afterOpen() {
      setTimeout(() => {
        QRCode.toCanvas(
          this.$refs.canvas,
          this.payUrl,
          { width: 300, height: 300 },
          function(error) {
            if (error) console.error(error);
            console.log("success!");
          }
        );
      }, 400);
    },
    countTime() {
      let date = new Date();
      let now = date.getTime();
      let endDate = new Date(this.ordertime * 1000); // 设置截止时间
      let end = endDate.getTime();
      let leftTime = end - now; // 时间差
      let m, s;
      if (leftTime >= 0) {
        m = Math.floor((leftTime / 1000 / 60) % 60);
        s = Math.floor((leftTime / 1000) % 60);

        if (s < 10) {
          s = "0" + s;
        }
        if (m < 10) {
          m = "0" + m;
        }
        this.timeOver = m + "分" + s + "秒";
        setTimeout(this.countTime, 100);
      } else {
        this.timeOver = "00分00秒";
      }
    },
    handleCommand(command) {
      this.inputType = command == "any";
    }
    // handleBlur (event) {
    //   let input = parseFloat(event.target.value)
    //   this.format(input)
    //   console.log(this.temp_amount)
    // },
    // handleChange (value) {
    //   let input = parseFloat(value)
    //   this.format(input)

    //   console.log(this.temp_amount)
    // },
    // format (input) {
    //   if (isNaN(input)) {
    //     this.temp_amount = 0
    //   }
    //   let yushu = (input * 100).toFixed(0) % 10
    //   if (yushu === 0) {
    //     this.temp_amount = input
    //   } else {
    //     this.temp_amount = (input * 100 - yushu) / 100
    //   }
    // }
  },
  watch: {
    $route(to, from) {
      this.activeName = "first";
    }
  }
};
</script>

<style lang="less" scoped>
@import "../../style/mixin";
.fix-width-frame {
  margin: 0 auto;
  width: 1000px;
}

.el-tabs {
  margin-top: 40px;
}

.label-title {
  font-weight: bold;
  font-size: 24px;
  color: #ff633b;
  margin: 30px;
}
.main-content {
  // padding: 0px 40px;
}

.balance {
  font-size: 16px;
  color: #222;
  font-weight: bold;
  margin: 30px 0;
}

.center {
  text-align: center;
  // display: inline-block;
}
.lineBox {
  line-height: 40px;
  border-top: gray solid 1px;
  border-bottom: gray solid 1px;
  margin-bottom: 30px;
}
.row {
  margin-bottom: 30px;
}

.tip {
  color: #555;
  font-size: 12px;
  margin-bottom: 10px;
  // margin-left: 20px;
}
.tip span {
  color: #f82a0f;
  // font-weight: bold;
}

.deposit-any {
  margin-top: 20px;
  margin-bottom: 40px;
}

.deposit-list {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  align-content: flex-start;

  margin-top: 20px;
  margin-bottom: 40px;

  .deposit-item {
    .wh(150px, 160px);
  }
}

.pay-container {
  text-align: center;
  .el-button {
    .wh(160px, 40px);
    border-radius: 2px;
  }
}
</style>
